import {login, logout, getInfo} from '@/api/login'
import { setToken, removeToken} from '@/utils/auth'
import {defineStore} from "pinia";


const useUserStore = defineStore("user", {
    state: () => ({
            token: '',
            jobNo: '',
            avatar: '',
            roles: [],
            loginFlag: false,
            user:null,
            permissions: []
        }
    ),
    actions: {
        // 登录
        loginAction(userInfo) {
            const jobNo = userInfo.jobNo.trim()
            const password = userInfo.password
            const code = userInfo.code
            const uuid = userInfo.uuid
            return new Promise((resolve, reject) => {
                login(jobNo, password, code, uuid).then(res => {
                    setToken(res.data)
                    this.token = res.data
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        getInfo() {
            return new Promise((resolve, reject) => {
                getInfo().then(res => {
                    const user = res.user
                    if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
                        this.roles = res.roles
                        this.permissions = res.permissions
                    } else {
                        this.roles = ['ROLE_DEFAULT']
                    }
                    this.jobNo = user.jobNo
                    this.avatar = user.avatar
                    this.user = res.user
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 退出系统
        logout() {
            return new Promise((resolve) => {
                logout(this.token).then(() => {
                    this.token = ''
                    this.roles = []
                    this.permissions = []
                    this.$reset()
                    removeToken()
                    console.log("退出成功")
                    resolve()
                }).catch(() => {
                })
            })
        }
    }, persist: {
        key: 'user',
        storage: sessionStorage
    }
})

export default useUserStore


